package com.example.logindemo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.example.logindemo.entity.Review;
import com.example.logindemo.entity.ReviewImage;
import com.example.logindemo.entity.RunOrder;
import com.example.logindemo.entity.User;
import com.example.logindemo.service.FileUploadService;
import com.example.logindemo.service.ReviewService;
import com.example.logindemo.service.RunOrderService;
import com.example.logindemo.service.ReviewImageService;
import com.example.logindemo.service.UserService;
import com.example.logindemo.security.SecurityUtil;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class ApiController {

    private final FileUploadService fileUploadService;
    private final RunOrderService runOrderService;
    private final ReviewService reviewService;
    private final ReviewImageService reviewImageService;
    private final UserService userService;
    
    @Autowired
    public ApiController(FileUploadService fileUploadService, 
                        RunOrderService runOrderService,
                        ReviewService reviewService,
                        ReviewImageService reviewImageService,
                        UserService userService) {
        this.fileUploadService = fileUploadService;
        this.runOrderService = runOrderService;
        this.reviewService = reviewService;
        this.reviewImageService = reviewImageService;
        this.userService = userService;
    }

    // 获取统计数据API
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getStatistics() {
        try {
            // 使用数据库统计数据
            Map<String, Object> stats = new HashMap<>();
            
            // 获取所有订单并在内存中计算统计数据
            List<RunOrder> allOrders = runOrderService.getAllRunOrders();
            
            // 计算总订单数和各状态订单数
            stats.put("totalOrders", allOrders.size());
            stats.put("pendingOrders", allOrders.stream().filter(o -> "pending".equals(o.getStatus())).count());
            stats.put("processingOrders", allOrders.stream().filter(o -> "processing".equals(o.getStatus())).count());
            stats.put("completedOrders", allOrders.stream().filter(o -> "completed".equals(o.getStatus())).count());
            stats.put("canceledOrders", allOrders.stream().filter(o -> "canceled".equals(o.getStatus())).count());
            
            // 计算待评价订单数
            long pendingReviews = allOrders.stream()
                    .filter(o -> "completed".equals(o.getStatus()) && "unreviewed".equals(o.getReviewStatus()))
                    .count();
            
            // 获取平均评分和总评价数
            Double averageRating = reviewService.getAverageRating();
            long totalReviews = reviewService.getTotalReviews();
            
            // 计算完成率
            long completedOrders = (long) stats.get("completedOrders");
            String completionRate = allOrders.size() > 0 ? String.format("%.1f%%", (double) completedOrders / allOrders.size() * 100) : "0%";
            
            stats.put("completionRate", completionRate);
            stats.put("pendingReviews", pendingReviews);
            stats.put("averageRating", averageRating != null ? averageRating : 0.0);
            stats.put("totalReviews", totalReviews);
            
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "获取统计数据失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    // 获取跑单列表API
    @GetMapping("/orders")
    public ResponseEntity<Map<String, Object>> getOrders(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String search,
            @RequestParam(required = false, defaultValue = "all") String status,
            @RequestParam(required = false, defaultValue = "all") String reviewStatus) {
        
        try {
            // 从数据库获取所有订单
            List<RunOrder> allOrders = runOrderService.getAllRunOrders();
            
            // 过滤订单
            List<RunOrder> filteredOrders = allOrders;
            
            if (search != null && !search.isEmpty()) {
                filteredOrders = filteredOrders.stream()
                        .filter(order -> order.getRunOrderId().contains(search) || 
                                         order.getOrderId().contains(search))
                        .collect(Collectors.toList());
            }
            
            if (!"all".equals(status)) {
                filteredOrders = filteredOrders.stream()
                        .filter(order -> status.equals(order.getStatus()))
                        .collect(Collectors.toList());
            }
            
            if (!"all".equals(reviewStatus)) {
                filteredOrders = filteredOrders.stream()
                        .filter(order -> reviewStatus.equals(order.getReviewStatus()))
                        .collect(Collectors.toList());
            }
            
            // 排序（按完成时间倒序）
            filteredOrders.sort((o1, o2) -> {
                if (o1.getCompletionTime() == null) return 1;
                if (o2.getCompletionTime() == null) return -1;
                return o2.getCompletionTime().compareTo(o1.getCompletionTime());
            });
            
            // 手动分页
            int start = (page - 1) * size;
            int end = Math.min(start + size, filteredOrders.size());
            List<RunOrder> pagedOrders = start < filteredOrders.size() ? filteredOrders.subList(start, end) : new ArrayList<>();
            
            // 将实体对象转换为响应格式
            List<Map<String, Object>> orders = pagedOrders.stream()
                    .map(this::convertRunOrderToMap)
                    .collect(Collectors.toList());
            
            // 构建响应
            Map<String, Object> response = new HashMap<>();
            response.put("orders", orders);
            response.put("currentPage", page);
            response.put("totalPages", (int) Math.ceil((double) filteredOrders.size() / size));
            response.put("totalElements", filteredOrders.size());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "获取订单列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    // 添加RunOrder实体转Map的辅助方法
    private Map<String, Object> convertRunOrderToMap(RunOrder runOrder) {
        Map<String, Object> orderMap = new HashMap<>();
        orderMap.put("id", runOrder.getId());
        orderMap.put("runOrderId", runOrder.getRunOrderId());
        orderMap.put("orderId", runOrder.getOrderId());
        orderMap.put("userName", runOrder.getUserName());
        orderMap.put("deliveryAddress", runOrder.getDeliveryAddress());
        orderMap.put("completionTime", runOrder.getCompletionTime() != null ? 
                    new SimpleDateFormat("yyyy-MM-dd HH:mm").format(runOrder.getCompletionTime()) : "");
        orderMap.put("deliveryPerson", runOrder.getDeliveryPerson());
        orderMap.put("status", runOrder.getStatus());
        orderMap.put("reviewStatus", runOrder.getReviewStatus());
        orderMap.put("hasReview", "reviewed".equals(runOrder.getReviewStatus()));
        return orderMap;
    }
    
    // 将Review实体转换为响应格式的Map对象
    private Map<String, Object> convertReviewToMap(Review review) {
        Map<String, Object> result = new HashMap<>();
        result.put("reviewId", review.getId());
        result.put("runOrderId", review.getRunOrderId());
        result.put("userId", review.getUserId());
        result.put("rating", review.getRating());
        result.put("content", review.getContent());
        result.put("reviewTime", review.getCreateTime());
        
        // 暂时不添加图片列表，因为Review实体没有直接的图片关联方法
        
        return result;
    }
    
    // 获取当前用户的跑单列表API
    @GetMapping("/my/orders")
    public ResponseEntity<Map<String, Object>> getMyOrders(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String search,
            @RequestParam(required = false, defaultValue = "all") String status,
            @RequestParam(required = false, defaultValue = "all") String reviewStatus) {
        
        try {
            // 获取当前登录用户
            String currentUsername = SecurityUtil.getCurrentUsername();
            if (currentUsername == null) {
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "用户未登录");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(error);
            }
            
            // 获取当前用户信息
            User currentUser = userService.getUserByUsername(currentUsername);
            if (currentUser == null) {
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "用户不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
            }
            
            // 获取当前用户的跑单数据
            List<RunOrder> userOrders = runOrderService.getRunOrdersByUserId(currentUser.getId());
            
            // 过滤订单
            List<RunOrder> filteredOrders = userOrders;
            
            if (search != null && !search.isEmpty()) {
                filteredOrders = filteredOrders.stream()
                        .filter(order -> order.getRunOrderId().contains(search) || 
                                         order.getOrderId().contains(search))
                        .collect(Collectors.toList());
            }
            
            if (!"all".equals(status)) {
                filteredOrders = filteredOrders.stream()
                        .filter(order -> status.equals(order.getStatus()))
                        .collect(Collectors.toList());
            }
            
            if (!"all".equals(reviewStatus)) {
                filteredOrders = filteredOrders.stream()
                        .filter(order -> reviewStatus.equals(order.getReviewStatus()))
                        .collect(Collectors.toList());
            }
            
            // 排序（按完成时间倒序）
            filteredOrders.sort((o1, o2) -> {
                if (o1.getCompletionTime() == null) return 1;
                if (o2.getCompletionTime() == null) return -1;
                return o2.getCompletionTime().compareTo(o1.getCompletionTime());
            });
            
            // 手动分页
            int start = (page - 1) * size;
            int end = Math.min(start + size, filteredOrders.size());
            List<RunOrder> pagedOrders = start < filteredOrders.size() ? filteredOrders.subList(start, end) : new ArrayList<>();
            
            // 将实体对象转换为响应格式
            List<Map<String, Object>> orders = pagedOrders.stream()
                    .map(this::convertRunOrderToMap)
                    .collect(Collectors.toList());
            
            // 构建响应
            Map<String, Object> response = new HashMap<>();
            response.put("orders", orders);
            response.put("currentPage", page);
            response.put("totalPages", (int) Math.ceil((double) filteredOrders.size() / size));
            response.put("totalElements", filteredOrders.size());
            response.put("userName", currentUser.getUsername()); // 当前用户名
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "获取用户订单列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    // 获取单个跑单详情
    @GetMapping("/orders/{runOrderId}")
    public ResponseEntity<?> getOrder(@PathVariable String runOrderId) {
        try {
            // 标准化runOrderId格式，确保包含RUN-前缀
            String cleanRunOrderId = runOrderId.startsWith("RUN-") ? runOrderId : "RUN-" + runOrderId;
            
            // 从数据库获取订单
            Optional<RunOrder> orderOpt = runOrderService.getRunOrderByRunOrderId(cleanRunOrderId);
            
            if (orderOpt.isPresent()) {
                RunOrder order = orderOpt.get();
                
                // 获取当前登录用户
                String currentUsername = SecurityUtil.getCurrentUsername();
                if (currentUsername == null) {
                    Map<String, Object> error = new HashMap<>();
                    error.put("success", false);
                    error.put("message", "用户未登录");
                    return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(error);
                }
                
                // 获取当前用户信息
                User currentUser = userService.getUserByUsername(currentUsername);
                if (currentUser == null) {
                    Map<String, Object> error = new HashMap<>();
                    error.put("success", false);
                    error.put("message", "用户不存在");
                    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
                }
                
                // 检查用户是否有权限访问此跑单（用户只能访问自己的跑单，管理员可以访问所有）
                boolean isAdmin = currentUser.getRoles().stream()
                    .anyMatch(role -> "ADMIN".equals(role.getName()));
                
                if (!isAdmin && !currentUser.getId().equals(order.getUserId())) {
                    Map<String, Object> error = new HashMap<>();
                    error.put("success", false);
                    error.put("message", "无权访问此跑单");
                    return ResponseEntity.status(HttpStatus.FORBIDDEN).body(error);
                }
                
                // 获取订单对应的评价（如果有）
                Optional<Review> reviewOpt = reviewService.getReviewByRunOrderId(cleanRunOrderId);
                Map<String, Object> orderMap = convertRunOrderToMap(order);
                
                if (reviewOpt.isPresent()) {
                    orderMap.put("review", convertReviewToMap(reviewOpt.get()));
                }
                
                return ResponseEntity.ok(orderMap);
            } else {
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "跑单不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
            }
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "获取订单详情失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    // 获取评价详情
    @GetMapping("/reviews/{runOrderId}")
    public ResponseEntity<?> getReview(@PathVariable String runOrderId) {
        try {
            // 标准化runOrderId格式
            String cleanRunOrderId = runOrderId.startsWith("RUN-") ? runOrderId : "RUN-" + runOrderId;
            
            // 从数据库获取评价
            Optional<Review> reviewOpt = reviewService.getReviewByRunOrderId(cleanRunOrderId);
            
            if (reviewOpt.isPresent()) {
                return ResponseEntity.ok(convertReviewToMap(reviewOpt.get()));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "获取评价详情失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    // 提交评价
    @PostMapping("/reviews")
    public ResponseEntity<Map<String, Object>> submitReview(
            @RequestParam String runOrderId,
            @RequestParam int rating,
            @RequestParam String content,
            @RequestParam(required = false) String tags,
            @RequestPart(required = false) List<MultipartFile> images,
            @RequestPart(required = false) List<MultipartFile> files) {
        try {
            // 标准化runOrderId格式
            String cleanRunOrderId = runOrderId.startsWith("RUN-") ? runOrderId : "RUN-" + runOrderId;
            
            // 参数验证
            if (rating < 1 || rating > 5) {
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "评分必须在1-5之间");
                return ResponseEntity.badRequest().body(error);
            }
            
            if (content == null || content.trim().isEmpty()) {
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "评价内容不能为空");
                return ResponseEntity.badRequest().body(error);
            }
            
            if (content.length() > 500) {
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "评价内容不能超过500字");
                return ResponseEntity.badRequest().body(error);
            }
            
            // 检查订单是否已评价
            if (reviewService.isOrderReviewed(cleanRunOrderId)) {
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "该订单已经评价过了，请使用编辑功能更新评价");
                return ResponseEntity.badRequest().body(error);
            }
            
            // 创建并保存评价（假设当前用户ID为1，用户名为张三）
            Map<String, Object> result = reviewService.submitReview(cleanRunOrderId, rating, content.trim(), tags != null ? tags.trim() : "", images, 1, "张三");
            
            // 获取保存的评价
            Review review = (Review) result.get("review");
            
            // 处理普通文件上传
            if (files != null && !files.isEmpty()) {
                for (MultipartFile file : files) {
                    if (!file.isEmpty() && file.getSize() <= 10 * 1024 * 1024) {
                        String fileName = fileUploadService.storeFile(file);
                        String downloadUrl = fileUploadService.getFileDownloadUri(fileName);
                        
                        // 这里应该将文件信息保存到数据库中，与评价关联
                        // 由于当前Review实体可能没有文件关联，这里仅做示例
                        System.out.println("保存评价附件: " + fileName);
                    }
                }
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "评价提交成功");
            response.put("review", convertReviewToMap(review));
            
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "提交评价失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    // 编辑评价
    @PutMapping("/reviews/{reviewId}")
    public ResponseEntity<Map<String, Object>> editReview(
            @PathVariable int reviewId,
            @RequestParam int rating,
            @RequestParam String content,
            @RequestParam(required = false) String tags,
            @RequestPart(required = false) List<MultipartFile> images,
            @RequestPart(required = false) List<MultipartFile> files,
            @RequestParam(required = false) List<String> removeImageIds,
            @RequestParam(required = false) List<String> removeFileIds) {
        try {
            // 参数验证
            if (rating < 1 || rating > 5) {
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "评分必须在1-5之间");
                return ResponseEntity.badRequest().body(error);
            }
            
            if (content == null || content.trim().isEmpty()) {
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "评价内容不能为空");
                return ResponseEntity.badRequest().body(error);
            }
            
            if (content.length() > 500) {
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "评价内容不能超过500字");
                return ResponseEntity.badRequest().body(error);
            }
            
            // 使用ReviewService更新评价
            Map<String, Object> result = reviewService.editReview(
                reviewId, 
                rating, 
                content.trim(),
                tags != null ? tags.trim() : "",
                images,
                removeImageIds
            );
            
            // 获取更新后的评价
            Review updatedReview = (Review) result.get("review");
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "评价更新成功");
            response.put("review", convertReviewToMap(updatedReview));
            
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "更新评价失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    // 删除评价
    @DeleteMapping("/reviews/{reviewId}")
    public ResponseEntity<Map<String, Object>> deleteReview(@PathVariable int reviewId) {
        try {
            // 使用ReviewService删除评价
            reviewService.deleteReview(reviewId);
            boolean deleted = true;
            
            if (deleted) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "评价删除成功");
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "评价不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
            }
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "删除评价失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
}